import { defineStore } from 'pinia';
import { DEFAULT_CACHE_PREFIX, saveStorage } from '@/utils';
import { login } from '@/api/login';

interface AppState {
  user: any;
  token: string;
  chatActive: Boolean;
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    user: null,
    token: '',
    chatActive: false, // 是否在生成中
  }),

  actions: {
    setUser(user: any) {
      this.user = user;
      saveStorage('user', JSON.stringify(user));
    },
    updateState(payload: any) {
      Object.assign(this, payload);
    },

    // 登录
    login(args: any) {
      login(args.data)
        .then((res: any) => {
          if (res.code === 200) {
            const { user, token }: any = res.data;
            this.token = token;
            this.setUser(user);
            saveStorage('token', token);
            args.success();
          }
        })
        .catch((error: any) => {
          args.open(error);
        });
    },

    // 退出登录
    logOut() {
      // 清除所有缓存
      localStorage.clear();
      sessionStorage.clear();
      this.user = null;
    },
  },
  persist: {
    key: `${DEFAULT_CACHE_PREFIX}app`, // 定义存储的前置key
    storage: sessionStorage, // 使用 sessionStorage
    // pick: null, // 持久化指定数据['user', 'token']  传递null undefault 缓存所有
  },
});
